package Backtracking;

import java.util.ArrayList;
import java.util.List;

/*
* 23. 括号生成
*
* */
public class GenerateParenthesis22 {
    List<String> res=new ArrayList<>();
    public List<String> generateParenthesis(int n) {
        if(n==0){
            return res;
        }
        dfs(new StringBuffer(),0,0,n);
        return res;
    }

    private void dfs(StringBuffer sb,  int left, int right, int n) {
        if(left==n && right==n){
            res.add(sb.toString());
            return;
        }
        if(left<n){
            sb.append('(');
            dfs(sb,left+1,right,n);
            sb.deleteCharAt(sb.length()-1);
        }
        if(right<left){
            sb.append(')');
            dfs(sb,left,right+1,n);
            sb.deleteCharAt(sb.length()-1);
        }

    }
}
